# A subscription means that a user want to be notified of changes to an issue
class Subscription < ActiveRecord::Base
  belongs_to :user, :counter_cache => :subscribed_issues_count
  belongs_to :issue, :counter_cache => :subscribers_count

  def self.subscribe( issue, user )
    if s = find( :first, :conditions =>
                 ['user_id = ? AND issue_id = ?', user, issue] )
      s
    else
      create( :issue => issue, :user => user )
    end
  end

  def self.unsubscribe( issue, user )
    if s = find( :first, :conditions =>
                 ['user_id = ? AND issue_id = ?', user, issue] )
      s.destroy
    end
  end

  def self.subscribed?( issue, user )
    s = find( :first, :conditions =>
                 ['user_id = ? AND issue_id = ?', user, issue] )
    return !s.nil?
  end
end
